package com.springboot.hiresystem.Tool;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
//使用 AES 加密算法实现可逆转换：
public class HashTool {
    private static final String AES_KEY = "MySecretKey12345"; // 密钥长度需为 16/24/32 字节

    // 加密（值 → 哈希）
    public static String encrypt(String value) throws Exception {
        SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // 解密（哈希 → 值）
    public static String decrypt(String hash) throws Exception {
        SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decoded = Base64.getDecoder().decode(hash);
        byte[] decrypted = cipher.doFinal(decoded);
        return new String(decrypted);
    }

    public static void main(String[] args) throws Exception {
        String original = "Hello World";
        String encrypted = encrypt(original);
        String decrypted = decrypt(encrypted);
        System.out.println("加密后: " + encrypted);
        System.out.println("解密后: " + decrypted);
    }
}